<template>
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from '@better-scroll/core'
import Pullup from '@better-scroll/pull-up'
import ScrollBar from '@better-scroll/scroll-bar'

BScroll.use(Pullup)
BScroll.use(ScrollBar)

export default {
  name: 'base-scroll',
  props: {
    // fixed: 当设置默认的 options 时，有时会导致 click 事件触发两次，原因不明
    options: { type: Object, require: true },
    data: { type: Array, default: () => [] }
  },
  data () {
    return {
      scroll: null
    }
  },
  mounted () {
    this.$nextTick(_ => {
      this.scroll = new BScroll(this.$refs.wrapper, this.options)
      // 初始化后定时刷新一次高度(因为此处 DOM 可能还没渲染完成)
      this.refresh()
    })
  },
  methods: {
    refresh () {
      this.scroll && this.scroll.refresh()
    },
    destroy () {
      this.scroll && this.scroll.destroy()
    },
    scrollTop () {
      this.scroll && this.scroll.scrollTo(0, 0, 1000)
    },
    scrollTo () {
      this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
    },
    scrollToElement () {
      this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
    },
    getScroll () {
      return this.scroll
    }
  },
  watch: {
    // 确保数据更新时刷新一次 scroll 的高度
    data () {
      this.$nextTick(_ => {
        this.refresh()
      })
    }
  }
}
</script>
